import dayjs from 'dayjs'
import { isWorkday } from 'chinese-workday'
import * as taskProjectApi from '@/api/taskProject'
import { onBeforeMount } from 'vue'
export const useWorkday = (autoLoad) => {
  const customWorkdayList = ref([])
  async function initCustomWorkday() {
    const { data } = await taskProjectApi.customWorkdayList()
    customWorkdayList.value = data.map((item) => item.calendarDate)
  }
  function isCustomWorkday(date) {
    return customWorkdayList.value.includes(dayjs(date).format('YYYY-MM-DD'))
  }
  function isAllWorkday(date) {
    return isWorkday(date) || isCustomWorkday(date)
  }
  function getRealDuration(start_time, end_time) {
    var bd = new Date(start_time),
      be = new Date(end_time)
    var bd_time = bd.getTime(),
      be_time = be.getTime(),
      time_diff = be_time - bd_time
    var d_arr = []
    for (var i = 0; i <= time_diff; i += 86400000) {
      var ds = new Date(bd_time + i)
      d_arr.push(ds)
    }
    const isStart = dayjs(end_time).format('HH:mm:ss') === '00:00:00' && isAllWorkday(end_time)
    const num = d_arr.filter((item) => isAllWorkday(item)).length
    // console.log(isStart, num)
    return isStart ? num - 1 : num
  }
  onBeforeMount(() => {
    if (autoLoad) {
      initCustomWorkday()
    }
  })
  return {
    customWorkdayList,
    initCustomWorkday,
    isWorkday,
    isCustomWorkday,
    isAllWorkday,
    getRealDuration,
  }
}
